﻿using System;
using System.Collections.Generic;
using OhioState.Graphics;
using Tao.OpenGl;

namespace OhioState.Graphics.OpenGL
{
    internal sealed class DepthBufferGL : IDepthBuffer, IOpenGLResource, IDisposable
    {
        public int Width { get; private set; }
        public int Height { get; private set; }
        public bool StencilSupport { get; private set; }

        public DepthBufferGL(int width, int height, bool stencilSupport)
        {
            this.Width = width;
            this.Height = height;
            this.StencilSupport = stencilSupport;
        }

        #region IHardwareResource<uint> Members
        public uint GUID
        {
            get
            {
                if (guid == 0)
                    CreateRenderBuffer();
                return guid;
            }
        }
        #endregion

        #region IDisposable Members
        public void Dispose()
        {
            if (guid != 0)
            {
                Gl.glDeleteRenderbuffersEXT(1, ref guid);
            }
            GC.SuppressFinalize(this);
        }
        #endregion

        private void CreateRenderBuffer()
        {
            Gl.glGenRenderbuffersEXT(1, out guid);
            Gl.glBindRenderbufferEXT(Gl.GL_RENDERBUFFER_EXT, guid);
            if (this.StencilSupport)
                Gl.glRenderbufferStorageEXT(Gl.GL_RENDERBUFFER_EXT, Gl.GL_DEPTH_STENCIL_EXT, this.Width, this.Height);
            else
                Gl.glRenderbufferStorageEXT(Gl.GL_RENDERBUFFER_EXT, Gl.GL_DEPTH_COMPONENT, this.Width, this.Height);
            Gl.glBindRenderbufferEXT(Gl.GL_RENDERBUFFER_EXT, 0);
        }

        private uint guid = 0;
    }
}
